import _ from "underscore";
import moment from "moment";

import Vue from 'vue';
import api from '../api';

import {
  mapState,
  mapActions
} from 'vuex'
let remindBtnsDef = [{ label: '提前时间<br/><span style="color:#666;font-size:12px;">任务结束前提前几分钟提醒</span>', type: 'info' }, { label: '提前05分钟', value: '5' },
  { label: '提前10分钟', value: '10' },
  { label: '提前15分钟', value: '15' },
  { label: '提前20分钟', value: '20' }
];
let remindTypeBtnsDef = [{ label: '闹钟提醒方式<br/><span style="color:#666;font-size:12px;">任务结束前和超时共2次提醒</span>', type: 'info' },
  { label: '系统闹钟', value: '1' },
  { label: '公众号提醒', value: '2' },
  { label: 'APP消息', value: '3' },
  { label: '短信提醒', value: '4' },
  { label: '电话呼叫', value: '5' }
];
export const logic = {
  computed: {
    ...mapState({
      remindMode: state => state.z39.remindMode,
    })
  },
  methods: {
    getDone2Due(task, startedVal) { //获取预计完成和提醒时间,超过24点会有bug.
      // task = this.taskitem ;
      var res = {};
      var dueDone = "";
      var remindTime = "";
      var tags = task.tags;
      if (tags && tags["due"] && tags["need"]) {
        let tempdue = startedVal || tags.started || tags.due;
        let need = tags.need;
        let dueDoneMom = moment(tempdue).add(getSecond(need), 's');
        // let temp = need.split(":");
        // let dueDoneMom = moment(due).add(temp[0], 'h').add(temp[1], 'm');
        dueDone = dueDoneMom.format('YYYY-MM-DD HH:mm');
        if (tags.remind) {
          var remind = tags.remind.split("_")[0];
          remindTime = dueDoneMom.subtract(remind, 'm').format('YYYY-MM-DD HH:mm');
        } else {
          remindTime = "";
        }
      }
      res = { dueDone, remindTime };
      // console.log("change clock:",dueDone,remindTime,remind);
      return res;
    },
    checkSetClock(task, startedVal) { //设置闹钟定时提醒,startedVal是修复doTaskEdit中数据还没返回的bug
      var clockKey, clockKey1, oldClock, oldClock1, key, key1, duration; //
      var tags = task.tags;
      if (tags == undefined) return;
      var remindT = tags.remind;
      if (task.state == "started" && remindT == undefined) remindT = "5_1";
      if ((tags.started == undefined && task.state != "started") || tags.need == undefined || remindT == undefined) return;
      var remindArr = remindT.split("_");
      var remind = remindArr[0];
      var remindValue = remindArr[1];
      var tagStarted = tags.started;
      var tagNeed = tags.need;
      // var tagDueDone = tags["started"];

      clockKey = "clock1_" + task.id;
      clockKey1 = "clock2_" + task.id;
      oldClock = localStorage.getItem(clockKey);
      oldClock1 = localStorage.getItem(clockKey1);
      if (oldClock) api.clockDel({ key: oldClock, ckey: clockKey });
      if (oldClock1) api.clockDel({ key: oldClock1, ckey: clockKey1 });
      let id = task.id;
      var { dueDone } = this.getDone2Due(task, startedVal);
      let time = dueDone.substr(11);
      let type = remindValue;
      // if (process.env.NODE_ENV == "development") type = 2;
      key = `task${id}_1-${time}_${type}`;
      key1 = `task${id}_2-${time}_${type}`;
      var started = new Date(tagStarted);
      var newTime = new Date();
      var temp, time1, time2, past;
      if (isNaN(tagNeed)) {
        temp = tagNeed.split(":");
        time1 = parseInt(temp[0]) * 60 * 60 + parseInt(temp[1]) * 60;
      } else {
        time1 = tagNeed;
      }
      // temp = this.remind.split(":");
      time2 = parseInt(remind) * 60;
      past = (newTime.getTime() - started.getTime()) / 1000 << 0;
      duration = time1 - time2 - past; //单位秒
      if (process.env.NODE_ENV == "development") duration = 2; //测试用,
      if (duration > 0) {
        api.clockAdd({ key, duration, ckey: clockKey }).then((data) => {
          if (data.errno != 0) return;
          localStorage.setItem(clockKey, key);
        })
      }
      let dueDoneTime = moment(dueDone).valueOf(); //dueDoneMom.getTime()
      duration = (dueDoneTime - newTime.getTime()) / 1000 << 0;
      if (process.env.NODE_ENV == "development") duration = 20; // 测试用
      if (duration > 0) {
        api.clockAdd({ key: key1, duration: duration, ckey: clockKey1 }).then((data) => {
          if (data.errno != 0) return;
          localStorage.setItem(clockKey1, key1);
        })
      }
      console.log("---duration:", dueDone, duration, key, tags)
    },
    setDueClock(task, due) {
      var clockKey, clockKey1, oldClock, oldClock1, key, key1, duration; //
      clockKey = "clock_" + task.id;
      clockKey1 = "clock1_" + task.id;
      oldClock = localStorage.getItem(clockKey);
      oldClock1 = localStorage.getItem(clockKey1);
      if (oldClock) api.clockDel({ key: oldClock, ckey: clockKey });
      if (oldClock1) api.clockDel({ key: oldClock1, ckey: clockKey1 });
      let id = task.id;
      let time = due.substr(11);
      let type1 = this.remindMode; // 2; // 
      let type = parseInt(type1) - 1; //1; // 
      if (process.env.NODE_ENV == "development") type = type1 = 2;
      key = `task${id}_0-${time}_${type}`;
      key1 = `task${id}_0-${time}_${type1}`;
      // var due = task.tags.due ;
      var dueMon = moment(due);
      duration = dueMon.diff(moment()) / 1000;
      if (process.env.NODE_ENV == "development") duration = 30; //测试用,
      if (duration > 0) {
        api.clockAdd({ key: key1, duration, ckey: clockKey1 }).then((data) => {
          if (data.errno != 0) return;
          localStorage.setItem(clockKey1, key1);
        })
      }
      dueMon.subtract(5, "m");
      duration = dueMon.diff(moment()) / 1000; //提前5分钟提醒.
      if (process.env.NODE_ENV == "development") duration = 4; //测试用,
      if (duration > 0) {
        api.clockAdd({ key, duration, ckey: clockKey }).then((data) => {
          if (data.errno != 0) return;
          localStorage.setItem(clockKey, key);
        })
      }
    },
    clearClock(task, state) { //删除任务的所有闹钟.根据任务状态自动删除.
      // 任务完成取消所有,任务开始取消准备提醒, 用户取消所有.1|2, 1所有 2准备 ~~3执行~~
      // 没有开始的任务是没有执行提醒.注意这里清除执行可能会导致Bug.
      // 如果是暂停也需要清楚执行闹铃. 特殊情况-任务重置或修改.
      var clockKey, clockKey1, oldClock, oldClock1, type; //
      // if (!type) { //没有传参,从任务状态判断删除闹铃.
      var s = state || task.state;
      if (s == 'started') type = 2;
      else if (s == "clear") return api.clockDel({ id: task.id, clear: 1 });
      else if (s == 'done' || s == 'cancelled' || s == 'toggle') type = 1;
      else if (s === 2) type = 2;
      // }
      if (!type) return; //如果没有对应状态就跳出逻辑.
      // 开始提醒准备提醒
      clockKey = "clock_" + task.id;
      clockKey1 = "clock0_" + task.id;
      oldClock = localStorage.getItem(clockKey);
      oldClock1 = localStorage.getItem(clockKey1);
      if (oldClock) api.clockDel({ key: oldClock, ckey: clockKey });
      if (oldClock1) api.clockDel({ key: oldClock1, ckey: clockKey1 });
      if (type == 1) { // 执行提醒
        clockKey = "clock1_" + task.id;
        clockKey1 = "clock2_" + task.id;
        oldClock = localStorage.getItem(clockKey);
        oldClock1 = localStorage.getItem(clockKey1);
        if (oldClock) api.clockDel({ key: oldClock, ckey: clockKey });
        if (oldClock1) api.clockDel({ key: oldClock1, ckey: clockKey1 });
      }
    },
    remindName2Val(name, type) { //type=1 | 2 ,1:提醒时间 2:提醒类型
      type = type || 1; //没传指时 默认为1
      var value = type == 1 ? 0 : 1; //默认值
      if (type == 1) {
        value = parseInt(name.substr(2, 4)) || 0; //'提前10分钟'
      } else {
        for (var i = remindTypeBtnsDef.length - 1; i >= 0; i--) {
          if (name == remindTypeBtnsDef[i].label) {
            value = remindTypeBtnsDef[i].value;
            break;
          }
        };
      }
      return value;
    }
  }

}
